<?php
/**
 * 微博 Oauth2.0 授权登录处理
 * date 2019-07-17
 */
namespace oauth;

class weibo
{
    private $app_key    = '';                               // 微博应用的 App Key
    private $app_secret = '';                               // 微博应用的 App Secret
    private $oauth2_url = 'https://api.weibo.com/oauth2';   // 微博OAuth2.0接口URL地址
    private $api2_url   = 'https://api.weibo.com/2';

    /**
     * 设置Key 和 Secret，如果为空，默认读取config/oauth.php文件里的 weibo_app_key和weibo_app_secret
     *
     * @param array $config 微博应用的Key和Secret值
     */
    public function __construct($config = [])
    {
        $this->app_key    = !empty($config['app_key']) ? $config['app_key'] : config('oauth.weibo_app_key');
        $this->app_secret = !empty($config['app_secret']) ? $config['app_secret'] : config('oauth.weibo_app_secret');
    }

    /**
     * 微博授权跳转URL
     * @param  string $redirect_uri 授权回调地址
     * @param  string $state        回调带回参数，防止CSRF攻击
     * @return mixed
     */
    public function authorize($redirect_uri = '', $state = '')
    {
        if (empty($redirect_uri)) return false;

        $url = $this->oauth2_url . '/authorize?client_id=' . $this->app_key . '&redirect_uri=' . $redirect_uri;
        $url = $url . '&response_type=code&state=' . $state;

        header('location: ' . $url);
    }

    /**
     * 获取微博access_token值
     * @param  string $redirect_uri 授权回调地址
     * @param  string $code         通过authorize获取的code值
     * @return mixed
     */
    public function getAccessToken($redirect_uri = '', $code = '')
    {
        if (empty($redirect_uri) || empty($code)) return false;

        $params = [
            'client_id'     => $this->app_key,
            'client_secret' => $this->app_secret,
            'grant_type'    => 'authorization_code',
            'redirect_uri'  => $redirect_uri,
            'code'          => $code,
        ];
        $url = $this->oauth2_url . '/access_token';
        $res = \util\Curl::curlPostRequest($url, $params);

        // 整理返回数据
        $res_data = [
            'app_account' => ['app_key' => $this->app_key, 'app_secret' => $this->app_secret],
            'res_json'    => $res
        ];

        return $res_data;
    }

    /**
     * 根据access_token和用户id获取用户信息
     * @param  string  $access_token token值
     * @param  integer $uid          微博用户id
     * @return array|void
     */
    public function getUserInfo($access_token = '', $uid = 0)
    {
        if (!$access_token || !$uid) return false;
        
        $url = $this->api2_url . '/users/show.json?access_token=' . $access_token . '&uid=' . $uid;
        $res = \util\Curl::curlGetRequest($url);

        return $res;
    }

}

